package com.ayh.campusfun.common.core.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ayh
 * @create 2021/4/27 0027 9:32
 * https configuration
 */

@Configuration
public class HttpsConfiguration {

    @Value("${http.port}")
    private int httpPort;

    @Value("${server.port}")
    private int serverPortHttps;


    /**
     * http 转 https
     */
    @Bean
    public Connector connector() {
//        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        Connector connector = new Connector(Http11NioProtocol.class.getName());
        connector.setScheme("http");
        // 监听的http端口
        connector.setPort(httpPort);
        connector.setSecure(false);
        // 监听到http端口后跳转的https端口
        connector.setRedirectPort(serverPortHttps);
        return connector;
    }

    /**
     * 拦截所有的请求
     */
    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
//                collection.addOmittedMethod(HttpMethod.OPTIONS.toString());
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(connector);
        return tomcat;
    }
}
